import 'package:cbec_app/components/base/base_chekbox.dart';
import 'package:cbec_app/components/base/base_function.dart';
import 'package:cbec_app/components/base/base_image.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/goods/goods_add_minus.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/components/popup/select_specifications_popup.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/EventMgr.dart';
import 'package:cbec_app/utils/ThemeConfig.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../pages/goods/binding/goods_detail_binding.dart';
import '../../pages/goods/view/goods_detail_page.dart';

///商品信息item
class GoodsInfoItem extends StatefulWidget {
  ///商品信息
  final Map<String, dynamic> goodsInfo;

  ///复选框选中回调
  final CallBackCheckbox? checkboxCallback;

  ///商品索引
  final int? index;

  ///商品分组索引
  final int? groupIndex;

  ///是否显示复选框
  final bool isShowCheckBox;

  ///标签
  final List<String>? tag;

  ///是否显示领券按钮
  final bool isShowCollectCoupon;

  ///商品信息显示样式
  final InfoStyle infoStyle;

  ///右下角按钮类型
  final RightBtnType btnType;

  ///右下角按钮购物车按钮点击
  final VoidCallback? rightBtnCarClick;

  ///右下角删除按钮点击
  final VoidCallback? rightBtnDeleteClick;

  ///间距
  final EdgeInsetsGeometry margin;

  ///边框圆角
  final double radius;

  ///规格是否可选
  final bool isCanSelect;

  ///是否显示商品数量
  final bool isShowGoodsNum;

  ///商品信息item(用于结算相关)
  const GoodsInfoItem({super.key, required this.goodsInfo, this.index = 0, this.groupIndex = 0, this.isShowCollectCoupon = false, this.infoStyle = InfoStyle.car, this.btnType = RightBtnType.none, this.radius = 8, this.checkboxCallback, this.tag, this.isShowCheckBox = true, this.margin = const EdgeInsets.all(0), this.rightBtnCarClick, this.rightBtnDeleteClick, this.isCanSelect = true, this.isShowGoodsNum = false});

  @override
  State<StatefulWidget> createState() {
    return _GoodsInfoItemState();
  }
}

class _GoodsInfoItemState extends State<GoodsInfoItem> {
  var curSeriesIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Container(margin: widget.margin, padding: EdgeInsets.only(left: 10.w, right: 10.w, top: 10.h, bottom: 10.h), decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(widget.radius))), child: _getInfoStyle());
  }

  @override
  void initState() {
    super.initState();
    print('tag ==== ${widget.tag}');
  }

  @override
  void dispose() {
    super.dispose();
  }

  ///商品图片
  Widget _goodsImg({double radius = 12, double? left}) {
    return Container(
      margin: EdgeInsets.only(left: left ?? 10.w),
      child: Stack(
        children: [
          BaseImage(
            url: widget.goodsInfo['mainImage'] ?? widget.goodsInfo['img'],
            width: 100.w,
            height: 100.w,
            borderRadius: BorderRadius.all(Radius.circular(radius)),
          ),
          widget.goodsInfo['isSend'] == 1 ? Positioned(child: BaseImage(url: 'zengson.png'), width: 80, height: 80) : const SizedBox()
        ],
      ),
    );
  }

  ///商品名称
  Widget _goodsName({double width = 0, int maxLines = 1}) {
    return Container(
      width: width,
      margin: EdgeInsets.only(top: 4.h),
      child: Text(
        widget.goodsInfo['commodityName'] ?? widget.goodsInfo['goodsName'],
        style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w400, color: ThemeConfig.mainTextColor),
        maxLines: maxLines,
        overflow: TextOverflow.ellipsis,
      ),
    );
  }

  ///商品规格
  Widget _goodsSpecifications() {
    return BaseInteractive(
      childWidget: Container(
        margin: EdgeInsets.only(top: 8.h),
        padding: EdgeInsets.only(top: 2.h, bottom: 2.h),
        decoration: widget.isCanSelect ? const BoxDecoration(color: Color(0xfff6f6f6), borderRadius: BorderRadius.all(Radius.circular(4))) : const BoxDecoration(),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(
              width: 194.w,
              child: Text(
                '${widget.goodsInfo['spuSpecJsonBody'] ?? (widget.goodsInfo['spuSpecBody'] ?? '')}',
                style: setTextStyle(11, FontWeight.w400, ThemeConfig.sectionTextColor),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            widget.isCanSelect
                ? const Icon(
                    Icons.keyboard_arrow_down,
                    size: 16,
                    color: ThemeConfig.sectionTextColor,
                  )
                : emptyWidget()
          ],
        ),
      ),
      onClick: () {
        if (widget.isCanSelect) {
          showSelectSpecificationsPopup(
              goodsInfo: widget.goodsInfo,
              price: widget.goodsInfo['price'].toString(),
              priceMarket: widget.goodsInfo['priceMarket'].toString(),
              // mainImg: widget.goodsInfo['mainImage'],
              goodsNum: widget.goodsInfo['buyNum'] as int);
        }
      },
    );
  }

  ///贸易标签
  Widget _tradeTag() {
    print('commodityType ==== ${widget.goodsInfo['commodityType']}');
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        if (widget.goodsInfo['commodityType'] != null) ...[
          goodsTypeTag(getGoodsTypeName(widget.goodsInfo['commodityType']), margin: const EdgeInsets.only(right: 5)),
        ],
        widget.isShowCollectCoupon
            ? Text(
                '领券',
                style: setTextStyle(10, FontWeight.w400, ThemeConfig.mainTextColor),
              )
            : emptyWidget()
      ],
    );
  }

  ///满减标签
  Widget _fullReduceTag() {
    return Padding(
      padding: EdgeInsets.only(top: 10.h),
      child: Row(
        children: [goodsFullReductionTag('满200-20', margin: EdgeInsets.only(right: 8)), goodsFullReductionTag('满6-5')],
      ),
    );
  }

  ///价格
  Widget _price() {
    return Padding(
        padding: EdgeInsets.only(top: 15.h),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                goodsSalesPrice(widget.goodsInfo['price'].toString()),
                widget.isShowGoodsNum
                    ? Padding(
                        padding: EdgeInsets.only(left: 8),
                        child: Text(
                          'x ${widget.goodsInfo['buyNum'].toString()}',
                          style: setTextStyle(10, FontWeight.w400, ThemeConfig.subTextColor),
                        ))
                    : emptyWidget()
                // Padding(
                //     padding: EdgeInsets.only(left: 8),
                //     child: goodsOriginPrice(
                //         widget.goodsInfo['priceMarket'] != null
                //             ? widget.goodsInfo['priceMarket'].toString()
                //             : widget.goodsInfo['price'].toString(),
                //         decoration: TextDecoration.lineThrough))
              ],
            ),
            _getBtnType()
          ],
        ));
  }

  ///商品信息显示样式
  Widget _getInfoStyle() {
    switch (widget.infoStyle) {
      case InfoStyle.car:
        return Row(
          children: [
            ///复选框
            InkWell(
              onTap: () {
                bool newValue = !(widget.goodsInfo['isSelect'] == 1);
                if (widget.checkboxCallback != null) {
                  widget.checkboxCallback!(widget.groupIndex!, widget.index!, newValue);
                }
                modifySelect(newValue);
              },
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 60), // 增大点击区域
                child: BaseCheckBox(
                  value: widget.goodsInfo['isSelect'] == 1,
                  onChange: (selected) {
                    if (widget.checkboxCallback != null) {
                      widget.checkboxCallback!(widget.groupIndex!, widget.index!, selected);
                    }
                    modifySelect(selected);
                  },
                ),
              ),
            ),

            ///商品图片
            _goodsImg(),

            ///商品信息
            Container(
              width: 194.w,
              margin: EdgeInsets.only(left: 18.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  ///贸易标签
                  _tradeTag(),

                  ///商品名称
                  _goodsName(width: 194.w),

                  ///商品规格
                  _goodsSpecifications(),

                  ///满减标签
                  // _fullReduceTag(),

                  ///价格
                  _price()
                ],
              ),
            )
          ],
        );

      case InfoStyle.collect:
        return BaseInteractive(
          onClick: () {
            final id = widget.goodsInfo['goodsId'];
            Get.to(
              () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
              routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
              arguments: {"id": id}, // 传递其它参数
              binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
            );
          },
          childWidget: Row(
            children: [
              widget.isShowCheckBox
                  ? BaseCheckBox(
                      value: widget.goodsInfo['isSelect'] == 1 ? true : false,
                      onChange: (selected) {
                        if (widget.checkboxCallback != null) {
                          widget.checkboxCallback!(widget.groupIndex!, widget.index!, selected);
                        }
                      },
                    )
                  : emptyWidget(),

              ///商品图片
              _goodsImg(),

              ///商品信息
              Container(
                width: 190.w,
                margin: EdgeInsets.only(left: 18.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    ///贸易标签
                    _tradeTag(),

                    ///商品名称
                    _goodsName(width: 190.w),

                    ///价格
                    _price()
                  ],
                ),
              )
            ],
          ),
        );
      case InfoStyle.settlement:
        return Row(
          children: [
            ///商品图片
            _goodsImg(),

            ///商品信息
            Container(
                width: 210.w,
                margin: EdgeInsets.only(left: 18.w),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        ///贸易标签
                        _tradeTag(),

                        ///商品名称
                        _goodsName(width: 158.w, maxLines: 2),
                      ],
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        ///价格
                        Text(
                          '￥${widget.goodsInfo['price']}',
                          style: setTextStyle(10, FontWeight.w500, ThemeConfig.mainTextColor),
                        ),

                        ///数量
                        Text(
                          '共${widget.goodsInfo['specNum']}${widget.goodsInfo['unit']}',
                          style: setTextStyle(11, FontWeight.w500, ThemeConfig.subTextColor),
                        )
                      ],
                    ),
                  ],
                ))
          ],
        );
      case InfoStyle.fillOrder:
        return Row(
          children: [
            ///商品图片
            _goodsImg(),

            ///商品信息
            Container(
              width: 194.w,
              margin: EdgeInsets.only(left: 18.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  ///贸易标签
                  // _tradeTag(),

                  ///商品名称
                  _goodsName(width: 194.w),

                  ///商品规格
                  // _goodsSpecifications(),

                  Container(
                    child: Row(
                      children: [
                        Text(
                          widget.goodsInfo['specNum'].toString(),
                          style: setTextStyle(11, FontWeight.w400, ThemeConfig.sectionTextColor),
                        ),
                        if (widget.goodsInfo['unit'] != null)
                          Text(
                            widget.goodsInfo['unit'],
                            style: setTextStyle(11, FontWeight.w400, ThemeConfig.sectionTextColor),
                          ),
                      ],
                    ),
                  ),

                  ///满减标签
                  // _fullReduceTag(),

                  ///价格
                  _price()
                ],
              ),
            )
          ],
        );
    }
  }

  ///获取按钮类型
  Widget _getBtnType() {
    switch (widget.btnType) {
      case RightBtnType.none:
        return emptyWidget();
      case RightBtnType.car:
        return BaseInteractive(onClick: widget.rightBtnCarClick, childWidget: BaseImage(url: "car_icon.png", width: 22.w, height: 22.w)
            // const Icon(
            //   Icons.shopping_cart,
            //   size: 21,
            // ),
            );
      case RightBtnType.addMinus:
        return GoodsAddMinus(
          num: widget.goodsInfo['buyNum'] ?? 1,
          onMinus: (goodsNum) {
            modifyNum(goodsNum);
          },
          onAdd: (goodsNum) {
            modifyNum(goodsNum);
          },
        );
      case RightBtnType.delete:
        return BaseInteractive(
          childWidget: BaseImage(url: 'delete_icon.png', width: 21, height: 21),
          onClick: widget.rightBtnDeleteClick,
        );
    }
  }

  ///修改购物车商品数量
  void modifyNum(int goodsNum) {
    Map<String, dynamic> params = {};
    params['buyNum'] = goodsNum;
    params['goodsId'] = widget.goodsInfo['goodsId'];
    params['specNum'] = widget.goodsInfo['specNum'];
    String carId = widget.goodsInfo['cartId'];
    Network.modifyCarGoods(params, carId).then((value) {
      EventMgr.send(EventType.refreshCar);
    });
  }

  ///修改购物车选中状态
  void modifySelect(bool isSelect) {
    Map<String, dynamic> params = {};
    params['isSelect'] = isSelect ? 1 : 0;
    params['goodsId'] = widget.goodsInfo['goodsId'];
    params['specNum'] = widget.goodsInfo['specNum'];
    params['buyNum'] = widget.goodsInfo['buyNum'];
    params['isSend'] = widget.goodsInfo['isSend'];
    String carId = widget.goodsInfo['cartId'];
    Network.modifyCarGoods(params, carId).then((value) {
      EventMgr.send(EventType.refreshCar);
    });
  }
}

///商品信息样式
enum InfoStyle {
  ///购物车
  car,

  ///收藏、足迹
  collect,

  ///结算
  settlement,

  ///填写订单
  fillOrder
}

///右下角按钮类型枚举
enum RightBtnType {
  ///不显示
  none,

  ///购物车按钮
  car,

  ///增减商品按钮组
  addMinus,

  ///删除商品
  delete
}
